﻿using PLCS.Application.Contracts.PLCConfigApp;
using PLCS.Application.Contracts.PLCConfigApp.Dtos;
using PLCS.Application.Contracts.PLCReadDataApp.Dtos;
using PLCS.Domain.PLCConfigs;
using PLCS.EntityFrameworkCore.PlcConfigs;

using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace PLCS.Application.PLCConfigApp;

public class PLCConfigAppService : CrudAppService<PLCConfig, PLCConfigDto, Guid, PagedResultRequestDto, PLCConfigEditDto>, IPLCConfigAppService
{
    private readonly IPLCConfigRepository _repository;

    public PLCConfigAppService(IPLCConfigRepository repository) : base(repository)
    {
        _repository = repository;
    }

    public async Task<PLCConfigDto> GetByPLCNoAsync(string pLCNo)
    {
        var entity = await _repository.FindByPLCNoAsync(pLCNo);
        Check.NotNull(entity, pLCNo, $"PLC‘{pLCNo}’不存在");
        return ObjectMapper.Map<PLCConfig, PLCConfigDto>(entity);
    }

    public async Task<IEnumerable<PLCConfigDto>> GetPlcConfigListAsync()
    {
        var entities = await Repository.GetListAsync();
        return await MapToGetListOutputDtosAsync(entities);
    }

    public async Task<PagedResultDto<PLCConfigDto>> GetListBySearchAsync(PagedResultRequestDto input, string? plcNo, string? ipAddress)
    {
        await CheckGetListPolicyAsync();

        var query = await CreateFilteredQueryAsync(input);
        query = query.WhereIf(!string.IsNullOrEmpty(plcNo), x => x.PLCNo == plcNo)
        .WhereIf(!string.IsNullOrEmpty(ipAddress), x => x.IPAddress == ipAddress);

        var totalCount = await AsyncExecuter.CountAsync(query);

        query = ApplyPaging(query, input);

        var entities = await AsyncExecuter.ToListAsync(query);
        var entityDtos = await MapToGetListOutputDtosAsync(entities);

        return new PagedResultDto<PLCConfigDto>(
            totalCount,
            entityDtos
        );
    }

    public async Task UpdateAsync(PLCConfigEditDto input)
    {
        await CheckUpdatePolicyAsync();
        var entity = await GetEntityByIdAsync(input.Id);
        await MapToEntityAsync(input, entity);
        await Repository.UpdateAsync(entity, autoSave: true);
    }
}